import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';

@Injectable()
export class GoodsService {
    constructor(@InjectModel('Goods') private readonly goodsModel) {}
    async find(query = {}) {
        const { page = 1, pageSize = 10 } = query as { page: number; pageSize: number };
        const aggregateOptions: any[] = [
            {
                $lookup: { localField: 'cate_id', foreignField: '_id', from: 'goods_cate', as: 'cate' },
            },
            { $unwind: '$cate' },
            {
                $lookup: {
                    localField: '_id',
                    foreignField: 'goods_id',
                    from: 'goods_attr',
                    as: 'goodsAttrs',
                    pipeline: [
                        {
                            $lookup: {
                                localField: 'attribute_id',
                                foreignField: '_id',
                                from: 'goods_type_attribute',
                                as: 'goodsTypeAttribute',
                            },
                        },
                        {
                            $unwind: '$goodsTypeAttribute',
                        },
                    ],
                },
            },
            {
                $lookup: {
                    localField: 'goods_color',
                    foreignField: '_id',
                    from: 'goods_color',
                    as: 'goods_color',
                },
            },
            { $skip: (+page - 1) * +pageSize },
            { $limit: +pageSize },
        ];
        const $match: any = {};
        if (JSON.stringify(query) !== '{}') {
            const { _id, title } = query as { _id: string; title: string };
            if (_id) {
                $match._id = new mongoose.Types.ObjectId(_id);
            }
            if (title) {
                $match.title = { $regex: new RegExp(title) };
            }
            aggregateOptions.unshift({ $match });
        }
        const data = await this.goodsModel.aggregate(aggregateOptions);
        const total = await this.goodsModel.find($match).count();
        return { data, total };
    }
    async create(goodsInfo) {
        return await this.goodsModel.create(goodsInfo);
    }
    async update(goodsInfo) {
        return await this.goodsModel.updateOne({ _id: goodsInfo._id }, goodsInfo);
    }
    async delete(goodsInfo) {
        return await this.goodsModel.deleteOne(goodsInfo);
    }
    getModel() {
        return this.goodsModel;
    }
}
